package com.linjuke.childay.activities;

import java.util.regex.Pattern;

import android.os.Bundle;
import android.telephony.PhoneNumberUtils;
import android.view.View;
import android.widget.EditText;

import com.linjuke.childay.R;
import com.linjuke.childay.activities.common.BaseActivity;
import com.linjuke.childay.androidext.ChildayApplication;
import com.linjuke.childay.common.PhoneHolder;
import com.linjuke.childay.common.ResultCodes;
import com.linjuke.childay.util.StringUtil;

public class InputPhoneActivity extends BaseActivity {

	private EditText phoneEditText;
	
	private static Pattern phonePattern = Pattern.compile("1\\d{10}");
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.input_phone);
		phoneEditText = (EditText) this.findViewById(R.id.input_phone_number);
		initViews();
	}

	public void handleSavePhone(View target) {
		String inputPhone = phoneEditText.getText().toString();
		if (!PhoneNumberUtils.isGlobalPhoneNumber(inputPhone) || !validate(inputPhone)) {
			this.toastLong(R.string.input_phone_invalidate_phone);
			return;
		}
		PhoneHolder.savePhone(this, inputPhone);
		this.setResult(ResultCodes.PHONE_SAVE_SUBMIT, this.getIntent());
		this.finish();
	}
	
	public void handleCancelPhone(View target) {
		this.setResult(ResultCodes.PHONE_SAVE_CANCEL, this.getIntent());
		this.finish();
	}
	
	private void initViews() {
		String phone = getInitPhone();
		phoneEditText.setText(phone);
	}

	private String getInitPhone() {
		String phone = PhoneHolder.getPhone(this);
		if (!StringUtil.isEmpty(phone)) {
			return phone;
		}
		return getInitPhoneFromSimCard();
	}

	private String getInitPhoneFromSimCard() {
		ChildayApplication childayApplication = ((ChildayApplication)getApplication());
		String phone = childayApplication.getTelephonyManager().getLine1Number();
		return StringUtil.isEmpty(phone) ? StringUtil.EMPTY_STRING : phone;
	}
	
	public static boolean validate(String fieldValue) {
		return phonePattern.matcher(fieldValue).matches();
	}

}
